﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ElectronicRecords.Models
{
    public class EquipmentsRepository
    {
        private ElectronicRecordsDataContext _datacontext;

        public EquipmentsRepository (ElectronicRecordsDataContext d)
        {
            _datacontext = d;
        }
        
        public IEnumerable<Equipments> GetEquipments()
        {
            if (_datacontext.Equipments.Count<Equipments>() != 0)
            {
                return _datacontext.Equipments.OrderBy(e => e.Name);
            }
            else return _datacontext.Equipments;
        }

        public Equipments GetEquipment(int equipmentId)
        {
            return _datacontext.Equipments.SingleOrDefault(e => e.ID_Equipment == equipmentId);
        }

        public Equipments CreateEquipment(string name, string description, bool isActive)
        {
            Equipments e = new Equipments{ Name = name, Description = description, Is_Active = isActive };
            
            _datacontext.Equipments.InsertOnSubmit(e);
            _datacontext.SubmitChanges();
            return e;
        }

        public Equipments CreateEquipment(Equipments e)
        {
            
            _datacontext.Equipments.InsertOnSubmit(e);
            _datacontext.SubmitChanges();
            return e;
        }

        public void UpdateEquipment(Equipments e)
        {
            Equipments dbEquipment = GetEquipment(e.ID_Equipment);
            dbEquipment.Name = e.Name;
            dbEquipment.Description = e.Description;
            dbEquipment.Is_Active = e.Is_Active;
            _datacontext.SubmitChanges();
        }

        public void DeleteEquipment(int equipmentId)
        {
            Equipments e = GetEquipment(equipmentId);
            _datacontext.Equipments.DeleteOnSubmit(e);
            _datacontext.SubmitChanges();
        }

        public IEnumerable<Equipments> FindEquipments(string strf)
        {
            return GetEquipments().Where(eq => (eq.Name.IndexOf(strf) > -1)).AsEnumerable<Equipments>();
        }

    }
}